﻿using Common;
using Domain.DbContext;
using FilterModel;
using System;
using System.Collections.Generic;
using System.Data.Entity.Core.Mapping;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Web;
using System.Web.Http;
using System.Web.SessionState;

namespace MainService
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Disabled); //全局禁用session

            //Webapi配置
            GlobalConfiguration.Configure(WebApiConfig.Register);

            //Ioc配置
            IocConfig.BuildWebapiContainer();

            //对象关系映射配置
            ObjectMapperConfig.RegisterMappings();

            //全局过滤器
            GlobalConfiguration.Configuration.Filters.Add(new GlobalExceptionFilter());
            GlobalConfiguration.Configuration.Filters.Add(new RequestMonitorActionFilter());

            #region EF初始化优化

            ////EF默认的数据库初始化器(四种初始化方式，只有禁用初始化器这种方式比较靠谱)
            System.Data.Entity.Database.SetInitializer<ModelContainer>(null);
            ////EF Migration作为数据库初始化器（发布部署应用程序的时候，当程序启动的时候它自动更新数据库，DbContext 第一次被使用的时候执行）
            //Database.SetInitializer(new MigrateDatabaseToLatestVersion<DbContext1, Configuration>());

            //首次使用EF的DbContext，内存中生成mapping views(耗时操作)
            ModelContainer dbContext = new ModelContainer();
            var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
            var mappingCollection = (StorageMappingItemCollection)objectContext.MetadataWorkspace.GetItemCollection(DataSpace.CSSpace);
            mappingCollection.GenerateViews(new List<EdmSchemaError>());

            #endregion

            LogHelper.Debug("*********************************Application_Start执行完毕****************************************");
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex = HttpContext.Current.Server.GetLastError();

            #region 跳转异常页前先记录异常

            Type exceptionType = typeof(Exception);
            if (ex.GetType() == exceptionType)//异常可能被Throw new Exception(e.Message);处理过
            {
                LogHelper.Error("异常可能被程序捕获处理(*^__^*):\r\n" + ex);
            }
            else
            {
                LogHelper.Error("异常未被程序捕获处理(●￣(ｴ)￣●):\r\n" + ex);
            }

            #endregion
        }

        protected void Application_End()
        {
            LogHelper.Debug("*********************************执行Application_End****************************************");
        }
    }
}
